<?php
declare(strict_types=1);

namespace app\index\controller;

use think\captcha\facade\Captcha;

class Feedback extends IndexBase
{
    public function verify(): \think\Response
    {
        return Captcha::create();
    }

    public function add(): \think\response\Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_CAPTCHA_ERROR_MESSAGE);
        }

        $code = $this->request->param('code', '', 'trim');
        if (!Captcha::check($code)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_CAPTCHA_ERROR_MESSAGE);
        }

        $formCode = $this->request->param('form_code', '', 'trim');
        if (empty($formCode)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $feedbackData          = [];
        $feedbackData['title'] = $this->request->param('title', '', 'trim');
        if (empty($feedbackData['title'])) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $extend = $this->request->param('extend', []);
        if ($extend) {
            foreach ($extend as $key => $value) {
                $feedbackData['extend_fields'][$key] = $value;
            }
        }

        $feedbackContent = new \app\common\business\FeedbackContent(session(self::_WEBSITE_CODE_SESSION_KEY), $formCode);
        $res             = $feedbackContent->addFeedbackContent($formCode, $feedbackData);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }
}